package com.gogowan.agroenterprise.storage;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.TitleActivity;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask.AsyncLoadListener;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask.InterActionModel;
import com.gogowan.agroenterprise.model.DealerModel;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.DealerRequest;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.utils.PalUtils;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.SideBar;
import com.gogowan.agroenterprise.widget.SideBar.OnTouchingLetterChangedListener;
import com.gogowan.agroenterprise.widget.SlideListView;
import com.gogowan.agroenterprise.widget.adapter.SlideBaseAdapter;
import com.gogowan.agroenterprise.widget.adapter.SlideViewHolder;
import com.gogowan.agroenterprise.widget.xlistview.LoadingLayout;
import com.google.gson.reflect.TypeToken;
import com.ioid.utils.JsonUtils;

import org.json.JSONObject;

/**
 * @Description:经销商列表
 * @author mdp
 * @date 2017年1月5日 上午11:05:53
 */
public class DealerListActivity extends TitleActivity implements
		AsyncLoadListener {

	private LoginResultInfo loginResult;
	private WeakRefAsyncTask weakRefAsyncTask = new WeakRefAsyncTask(this);
	private EditText dealer_list_search_et;
	private SlideListView lvcountryListView;
	private LoadingLayout loadingLayout;
	private TextView dialogText;
	private SideBar sideBar;
	private static final int REFRESH_RQT = 1;
	private static final int DEL_RQT = 2;
	private static final int REFRESH_HDL = 1;
	private static final int RELOAD_HDL = 2;
	private static final int NULL_HDL = 3;
	private static final int ADD_RQC = 1;
	private static final int EDIT_RQC = 2;
	private String[] zimu = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
			"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
			"X", "Y", "Z", "#" };
	private List<DealerModel> currentDataList = new ArrayList<DealerModel>();
	private List<DealerModel> sourceDataList = new ArrayList<DealerModel>();
	private ListBaseAdapter mListAdapter;

	@Override
	protected int setContentViewID() {
		return R.layout.activity_dealer_list;
	}

	@Override
	protected boolean initData(Intent intent, Bundle savedInstanceState) {
		loginResult = PalUtils.getLoginResultInfo(getApplicationContext());
		return loginResult != null;
	}

	@Override
	protected void initView() {
		initTitle("经销商管理", true);
		dealer_list_search_et = (EditText) findViewById(R.id.dealer_list_search_et);
		// 根据输入框输入值的改变来过滤搜索
		dealer_list_search_et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// localSearch(s);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		findViewById(R.id.dealer_list_search_im).setOnClickListener(this);
		lvcountryListView = (SlideListView) findViewById(R.id.dealer_list_lvcountry);
		dialogText = (TextView) findViewById(R.id.dealer_list_dialog);
		sideBar = (SideBar) findViewById(R.id.dealer_list_sidrbar);
		sideBar.setTextView(dialogText);
		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = mListAdapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					lvcountryListView.setSelection(position);
				}
			}
		});
		mListAdapter = new ListBaseAdapter(this, currentDataList,
				R.layout.layout_dealer_list_item, R.layout.slide_content);
		lvcountryListView.setAdapter(mListAdapter);
		lvcountryListView
				.setOnSlideItemClickListener(new SlideListView.OnSlideItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						if (currentDataList.get(position).getEnglishName()
								.indexOf("first") == -1) {
							Intent intent = new Intent(DealerListActivity.this,
									DealerDetailsActivity.class);
							intent.putExtra(PalUtils.PACK_TYPE_ITT, 2);
							intent.putExtra(PalUtils.PACK_MODEL_ITT,
									currentDataList.get(position));
							startActivityForResult(intent, EDIT_RQC);
						}
					}
				});
		loadingLayout = (LoadingLayout) findViewById(R.id.dealer_list_loadingLayout);
		loadingLayout.setReplacedView(findViewById(R.id.dealer_list_ll));
		requestList();
	}

	@Override
	protected void initTitle(String title, boolean isShowRight) {
		super.initTitle(title, isShowRight);
		ImageView all_top_right_im = (ImageView) findViewById(R.id.all_top_right_im);
		all_top_right_im.setVisibility(View.VISIBLE);
		all_top_right_im.setImageResource(R.drawable.add);
		all_top_right_im.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(DealerListActivity.this,
						DealerDetailsActivity.class);
				intent.putExtra(PalUtils.PACK_TYPE_ITT, 1);
				startActivityForResult(intent, ADD_RQC);
			}
		});
	}

	@Override
	protected void onClicked(View v) {
		switch (v.getId()) {
		case R.id.dealer_list_search_im:
			localSearch(dealer_list_search_et.getText().toString().trim());
			break;
		}
	}

	@Override
	public void handleMessage(TitleActivity activity, android.os.Message msg) {
		hideProgressDialog();
		switch (msg.what) {
		case NULL_HDL:
			loadingLayout.showNull(new LoadingLayout.OnNullClickListener() {
				@Override
				public void onClick() {
					requestList();
				}
			});
			break;
		case RELOAD_HDL:
			loadingLayout.showReload(new LoadingLayout.OnReloadClickListener() {
				@Override
				public void onClick() {
					requestList();
				}
			});
			break;
		case REFRESH_HDL:
			if (isAlreadyDestroyed()) {
				return;
			}
			mListAdapter.notifyDataSetChanged();
			loadingLayout.hide();
			break;
		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PalUtils.MsgType.DeleteDealer:
				// 增改
			case ADD_RQC:
			case EDIT_RQC:
				requestList();
				break;
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		weakRefAsyncTask.cancel();
	}

	@Override
	public void onResult(AsyncLoadListener asyncLoadListener, String response,
			int actionId) {
		hideProgressDialog();
		if (isAlreadyDestroyed()) {
			return;
		}
		if (PalUtils.isEmpty(response)) {
			if (actionId == REFRESH_RQT) {
				getWeakRefHandler().sendEmptyMessage(RELOAD_HDL);
			}
			PalUtils.showShortToast(getApplicationContext(),
					getString(R.string.server_error));
		} else {
			switch (actionId) {
			// 获取经销商列表
			case REFRESH_RQT:
				try {
					JSONObject jo=new JSONObject(response);
					if(jo.getInt("code")!=200){
						Toast.makeText(getApplicationContext(),jo.getString("msg"),Toast.LENGTH_LONG).show();
						return;
					}
					response=jo.getJSONArray("data").toString();
				}catch (Exception e){

				}
				Type userListType = new TypeToken<List<DealerModel>>(){}.getType();
				List<DealerModel> storeListResult= (List<DealerModel>) JsonUtils.fromJSON(response, userListType);
//				List<DealerModel> storeListResult = (List<DealerModel>) PalUtils
//						.getDataByTypeResult(response, userListType);
				if (storeListResult == null) {
					getWeakRefHandler().sendEmptyMessage(RELOAD_HDL);
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (storeListResult.size() > 0) {
					if (PalUtils.isEmpty(storeListResult)) {
						getWeakRefHandler().sendEmptyMessage(NULL_HDL);
						return;
					}
					sourceDataList.clear();
					sourceDataList.addAll(storeListResult);
					for (int i = 0; i < sourceDataList.size(); i++) {
						if (PalUtils.isEmpty(sourceDataList.get(i)
								.getEnglishName())) {
							String pinyin = PalUtils.getPinYin(sourceDataList
									.get(i).getSupplier());
							if (!PalUtils.isEmpty(pinyin)
									&& !Character.isLetter(pinyin.charAt(0))) {
								pinyin = "#";
							} else if (PalUtils.isEmpty(pinyin)) {
								pinyin = "#";
							}
							sourceDataList.get(i).setEnglishName(
									pinyin.toUpperCase(Locale.getDefault()));
						} else {
							sourceDataList.get(i).setEnglishName(
									sourceDataList.get(i).getEnglishName()
											.toUpperCase(Locale.getDefault()));
						}
					}
					localSearch("");
				} else {
					getWeakRefHandler().sendEmptyMessage(RELOAD_HDL);
					PalUtils.showShortToast(getApplicationContext(),
							"暂无经销商");
				}
				break;
			// 删除
			case DEL_RQT:
				ResultInfo resultInfo = (ResultInfo) PalUtils.getPostResult(
						response, ResultInfo.class);
				if (resultInfo == null) {
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (resultInfo.getResult() > 0) {
					PalUtils.showShortToast(getApplicationContext(),
							resultInfo.getResultinfo());
					requestList();
				} else {
					PalUtils.showShortToast(getApplicationContext(),
							resultInfo.getResultinfo());
				}
				break;
			}
		}
	}

	/**
	 * 请求经销商列表
	 * */
	private void requestList() {
		loadingLayout.showLoading();
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(REFRESH_RQT);
		interActionModel.setUrl(getString(R.string.first_url)
				+ getString(R.string.getSupplierList)+"?personid="+ MyApplication.mSettings.getLong("personid",0));
		interActionModel.setRequestType("get");
		weakRefAsyncTask.execute(interActionModel);
	}

	/**
	 * 删除经销商
	 * */
	private void deleteRequest(long dealerId) {
		showProgressDialog(getString(R.string.committing));
		DealerRequest dealerRequest = new DealerRequest();
		//dealerRequest.setEnterpriseID(loginResult.getEnterpriseinfo()
				//.getEnterpriseid());
		//dealerRequest.setUserID(loginResult.getUserinfo().getPersonid());
		//dealerRequest
				//.setUserType(loginResult.getEnterpriseinfo().getUserType());
		dealerRequest.setDealerID(dealerId);
		String json = Utils.toJSON(dealerRequest);
		Message message = new Message(PalUtils.MsgType.DelDealer,
				PalUtils.ENCRYPT, json);
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(DEL_RQT);
		interActionModel.setUrl(getString(R.string.first_url)
				+ getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);
	}

	/**
	 * 列表过滤
	 * */
	private void localSearch(CharSequence s) {
		if (PalUtils.isEmpty(s.toString())) {
			currentDataList.clear();
			currentDataList.addAll(sourceDataList);
		} else {
			String filterStr = s.toString().trim();
			currentDataList.clear();
			if (sourceDataList != null && sourceDataList.size() != 0) {
				for (DealerModel dealerModel : sourceDataList) {
					String name = dealerModel.getSupplier();
					String ename = dealerModel.getEnglishName();
					String phone = dealerModel.getPhoneNum();
					if (name.indexOf(filterStr) != -1
							|| ename.toUpperCase(Locale.getDefault())
									.startsWith(
											filterStr.toUpperCase(Locale
													.getDefault()))
							|| ename.toUpperCase(Locale.getDefault())
									.startsWith(
											filterStr.toUpperCase(Locale
													.getDefault()))
							|| phone.startsWith(filterStr)) {
						currentDataList.add(dealerModel);
					}
				}
			}
		}
		// 根据a-z进行排序源数据
		Collections.sort(currentDataList, new PinyinComparator());
		for (int i = 0; i < zimu.length; i++) {
			for (int x = 0; x < currentDataList.size(); x++) {
				String iii = currentDataList.get(x).getEnglishName()
						.substring(0, 1).toUpperCase(Locale.getDefault());
				if (iii.toUpperCase(Locale.getDefault()).equals(zimu[i])) {
					DealerModel storeModel = new DealerModel();
					storeModel.setEnglishName(zimu[i] + "first");
					currentDataList.add(x, storeModel);
					break;
				}
			}
		}
		getWeakRefHandler().sendEmptyMessage(REFRESH_HDL);
	}

	/**
	 * Adapter
	 */
	private class ListBaseAdapter extends SlideBaseAdapter<DealerModel>
			implements SectionIndexer {

		private List<DealerModel> dataList;

		public ListBaseAdapter(Context context, List<DealerModel> dataList,
				int itemLayoutId, int slideLayoutId) {
			super(context, dataList, itemLayoutId, slideLayoutId);
			this.dataList = dataList;
		}

		@Override
		public void convert(SlideViewHolder holder, final DealerModel bean,
				int position) {
			TextView tvLetter = holder.getView(R.id.dealer_list_item_catalog);
			RelativeLayout dealer_list_item_content_rl = holder
					.getView(R.id.dealer_list_item_content_rl);
			TextView dealer_list_item_name_tv = holder
					.getView(R.id.dealer_list_item_name_tv);
			TextView dealer_list_item_addr_tv = holder
					.getView(R.id.dealer_list_item_addr_tv);
			TextView dealer_list_item_tel_tv = holder
					.getView(R.id.dealer_list_item_tel_tv);
			Button deleteButton = holder.getView(R.id.deleteButton);
			deleteButton.setOnClickListener(new ButtonClickListener(position));
			if (bean.getEnglishName().substring(1).equals("first")) {
				tvLetter.setVisibility(View.VISIBLE);
				dealer_list_item_content_rl.setVisibility(View.GONE);
				tvLetter.setText(bean.getEnglishName().subSequence(0, 1));
				holder.getConvertView().setCanLeftSlide(false);
			} else {
				tvLetter.setVisibility(View.GONE);
				dealer_list_item_content_rl.setVisibility(View.VISIBLE);
				dealer_list_item_name_tv.setText(bean.getSupplier());
				dealer_list_item_addr_tv.setText(bean.getAddress());
				dealer_list_item_tel_tv.setText(bean.getPhoneNum());
				if (!PalUtils.isEmpty(bean.getPhoneNum())) {
					dealer_list_item_tel_tv
							.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View v) {
									startActivity(PalUtils.getCallIntent(
											bean.getPhoneNum(), false));
								}

							});
				}
				holder.getConvertView().setCanLeftSlide(true);
			}
		}

		class ButtonClickListener implements OnClickListener {

			private int position = 0;

			public ButtonClickListener(int position) {
				this.position = position;
			}

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.deleteButton:
					deleteRequest(currentDataList.get(position).getId());
					break;
				}
			}
		}

		@Override
		public Object[] getSections() {
			return null;
		}

		@Override
		public int getSectionForPosition(int position) {
			return 0;
		}

		@Override
		public int getPositionForSection(int sectionIndex) {
			for (int i = 0; i < getCount(); i++) {
				String sortStr = dataList.get(i).getEnglishName();
				char firstChar = sortStr.toUpperCase(Locale.getDefault())
						.charAt(0);
				if (firstChar == sectionIndex) {
					return i;
				}
			}
			return -1;
		}

	}

	/**
	 * 拼音排序规则
	 */
	private static class PinyinComparator implements Comparator<DealerModel> {

		@Override
		public int compare(DealerModel o1, DealerModel o2) {
			if (o1.getEnglishName().substring(0, 1).equals("@")
					|| o2.getEnglishName().substring(0, 1).equals("#")) {
				return -1;
			} else if (o1.getEnglishName().substring(0, 1).equals("#")
					|| o2.getEnglishName().substring(0, 1).equals("@")) {
				return 1;
			} else {
				return o1.getEnglishName().substring(0, 1)
						.compareTo(o2.getEnglishName().substring(0, 1));
			}
		}
	}
}
